<?php
/**
 * @Author:      zwh
 * @DateTime:    2016-12-26 15:33:57
 * @Description: 应收收回
 */
class ScsReceivableController extends BaseController
{
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-26 15:40:44
     * @Description: 收款单列表
     */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $receivable_id=Input::get('receivable_id');
            
            $rb=Receivable::where('receivable.shop_id',$sc_user->shop_id)
            ->leftJoin('sc_user as sc1','sc1.id','=','receivable.created_by')
            ->leftJoin('sc_user as sc2','sc2.id','=','receivable.verify_by')
            ->leftJoin('companys','companys.id','=','receivable.company_id')
            ->orderBy("receivable.verify_time","desc")
            ->where('receivable.status',1);
            if(Input::get('begin_data') && Input::get('end_data')){
                $rb->whereBetween('receivable.created_at',array(Input::get('begin_data').' 00:00:00',Input::get('end_data').' 23:59:59'));
            }
            if($receivable_id!=""){
                $rb=$rb->where(function($query)use ($receivable_id){
                    $query->where('receivable_id','like','%'.$receivable_id.'%')
                    ->orWhere('companys.name','like','%'.$receivable_id.'%');
                });
            }
            $count=$rb->count();
            $rb=$rb->skip($page_size*($page-1))->take($page_size)->select('receivable.receivable_id','companys.name as company_name','receivable.amount','receivable.note','sc1.real_name as create_user','sc2.real_name as verify_user','receivable.verify_status','receivable.verify_time','receivable.created_at','receivable.type')->get();
            foreach ($rb as $_rb) {
                $_rb->amount=bcdiv($_rb->amount,100,2);
            }
            $company=Companys::all();
            //所有企业的欠款统计
            $order_a_array=$return_a_array=$b_a_array=array();
            $order_amount=DB::select("select o.pay_user_id,sum(opr.amount) as amount from order_pay_record opr join orders o on o.order_id=opr.order_id JOIN users on users.id=o.pay_user_id where opr.pay_type=6 and opr.`status`=1 and users.type=2 and o.place=2 and o.shop_id=? and o.verify_status=0  and o.`status` in (1018,1017,1217,1317,1417)  group by o.pay_user_id",array($sc_user->shop_id));
            foreach ($order_amount as $_oa) {
                $order_a_array[$_oa->pay_user_id]=$_oa->amount/100;
            }
            //统计所有企业 洗车单欠款
            $wash_order_amount=DB::select("SELECT cwo.user_id,sum(cwopr.amount) as amount FROM  car_wash_order_pay_record cwopr LEFT JOIN car_wash_order cwo ON cwo.order_id = cwopr.order_id LEFT JOIN users u ON u.id = cwo.user_id WHERE  cwopr.pay_type = 6 AND cwopr.`status` = 1 AND u.type = 2 AND cwo.verify_status = 0 and cwo.`status`=1417 and cwo.shop_id=? group by cwo.user_id",array($sc_user->shop_id));
            foreach ($wash_order_amount as $_oa) {
                if(isset($order_a_array[$_oa->user_id])){
                    $order_a_array[$_oa->user_id]=$order_a_array[$_oa->user_id]+$_oa->amount/100;
                }else{
                    $order_a_array[$_oa->user_id]=$_oa->amount/100;
                }               
            }

            //所有的 套餐卡销售退款
            $sc_order_amount=DB::select("SELECT sco.user_id,sum(cwopr.amount) as amount FROM  service_card_order_pay_record cwopr LEFT JOIN service_card_order sco ON sco.order_id = cwopr.order_id LEFT JOIN users u ON u.id = sco.user_id WHERE  cwopr.pay_type = 6 AND cwopr.`status` = 1 AND u.type = 2 AND sco.verify_status = 0 and sco.`status`=1417 and sco.shop_id=? group by sco.user_id",array($sc_user->shop_id));
            foreach ($sc_order_amount as $_oa) {
                if(isset($order_a_array[$_oa->user_id])){
                    $order_a_array[$_oa->user_id]=$order_a_array[$_oa->user_id]+$_oa->amount/100;
                }else{
                    $order_a_array[$_oa->user_id]=$_oa->amount/100;
                }               
            }

            //所有企业的欠款退货统计 
            $return_amount=DB::select("select o.pay_user_id,sum(ror.amount) as amount from return_order_record  ror join return_order ro on ro.id=ror.return_order_id join orders o on o.order_id =ro.order_id  join users on users.id =o.pay_user_id where ror.pay_type=6 and ro.`status`=1 and users.type=2 and o.place=2 and o.shop_id=? and ro.verify_status=0 group by o.pay_user_id",array($sc_user->shop_id));
            foreach ($return_amount as $_oa) {
                $return_a_array[$_oa->pay_user_id]=$_oa->amount/100;
            }
            //所有企业的洗车单欠款退货 
            $car_return_amount=DB::select("SELECT  cwo.user_id,sum(rwr.amount) as amount
                FROM `return_washorder_record` rwr
                LEFT JOIN return_carwash_order rco ON rco.id = rwr.return_washorder_id
                LEFT JOIN car_wash_order cwo ON cwo.order_id = rco.order_id
                LEFT JOIN users u ON u.id = cwo.user_id where rwr.pay_type=6 AND rco.`status` = 1 and u.type=2 and rco.verify_status=0 and cwo.shop_id=? group by cwo.user_id",array($sc_user->shop_id));
            foreach ($car_return_amount as $_oa) {                
                if(isset($return_a_array[$_oa->user_id])){
                    $return_a_array[$_oa->user_id]=$return_a_array[$_oa->user_id]+$_oa->amount/100;
                }else{
                    $return_a_array[$_oa->user_id]=$_oa->amount/100;
                }  
            }

            //所有套餐卡销售退款
            $service_return_amount=DB::select("SELECT   sco.user_id,sum(rscr.amount) as amount
                FROM
                return_service_card_record rscr
                LEFT JOIN return_service_card_order rsco ON rsco.id = rscr.return_order_id
                LEFT JOIN service_card_order sco ON sco.order_id = rsco.order_id
                left join users on users.id= sco.user_id where rscr.pay_type=6 and users.type=2 and rsco.status=1 and sco.verify_status=0 and sco.shop_id=? group by sco.user_id",array($sc_user->shop_id));
            foreach ($service_return_amount as $_oa) {                
                if(isset($return_a_array[$_oa->user_id])){
                    $return_a_array[$_oa->user_id]=$return_a_array[$_oa->user_id]+$_oa->amount/100;
                }else{
                    $return_a_array[$_oa->user_id]=$_oa->amount/100;
                }  
            }



            //该店的 期初企业欠款
            $begin_amount=DB::select("SELECT * FROM `begin_arrear` where shop_id=?",array($sc_user->shop_id));
            foreach ($begin_amount as $ba) {
                $b_a_array[$ba->company_id]=$ba->current_amount/100;
            }
            foreach ($company as $c) {
                $c->order_amount=(isset($order_a_array[$c->id])?$order_a_array[$c->id]:0)-(isset($return_a_array[$c->id])?$return_a_array[$c->id]:0);
                $c->begin_amount=isset($b_a_array[$c->id])?$b_a_array[$c->id]:0;
            }

            $response['result']=array('count'=>$count,'receivable'=>$rb,'companys'=>$company);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-26 15:40:44
     * @Description: 企业欠款单（包含退货单）列表
     */
    public function order_lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'company_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $company_id=Input::get('company_id');
            $order_type=Input::get('order_type');
            $company=Companys::find($company_id);
            $company_name=$company->name;
            $temp_array=array();
            
            //所有拥有挂账支付方式的企业订单
            if($order_type==""||$order_type==0){
                $orders=OrderPayRecord::join('orders', 'order_pay_record.order_id', '=', 'orders.order_id')
                ->join('users','orders.pay_user_id', '=' ,'users.id')
                ->where('order_pay_record.pay_type',6)
                ->where('order_pay_record.status',1)
                ->where('users.type',2)
                ->where('users.status',1)
                ->where('orders.shop_id',$sc_user->shop_id)
                ->where('orders.pay_user_id',$company_id)
                ->whereIn('orders.status',array(1018,1017,1217,1317,1417))
                ->where('orders.place',2)
                ->select(array('orders.pay_user_id','users.real_name as company_name','orders.order_id','order_pay_record.amount',
                    'orders.pay_time as complete_time','orders.car_no','orders.car_no','orders.verify_status','orders.verify_time',
                    'orders.car_brand_id as car_brand_id','orders.car_brand_name as car_brand_name',
                    'orders.car_series_id as car_series_id','orders.car_series_name as car_series_name',
                    'orders.car_model_id as car_model_id','orders.car_model_name as car_model_name',
                    'orders.car_model_name as model'))
                ->orderBy('orders.user_id','asc');
                if(Input::get('verify_status')!=""){
                    $orders=$orders->where('orders.verify_status',Input::get('verify_status'));
                }
                if(Input::get('car_no')!=""){
                    $orders=$orders->where('orders.car_no','like','%'.Input::get('car_no').'%');
                }
                if(Input::get('complete_time')!=""){
                    $arr=explode('~',Input::get('complete_time'));
                    $orders=$orders->whereBetween('orders.pay_time',array($arr[0]." 00:00:00",$arr[1]." 23:59:59"));
                }
                if(Input::get('order_id')!=""){
                    $orders=$orders->where('orders.order_id','like','%'.Input::get('order_id').'%');
                }
                $orders=$orders->get();            
                foreach ($orders as $order) {
                    $order->return_type=0;
                    $order->amount=bcdiv($order->amount,100,2);
                    $order->order_type=0;
                    $temp_array[]=$order;
                }
            }
            
            if($order_type==""||$order_type==1){
                //用于挂账的洗车单
                $cwr_orders=CarWashOrderPayRecord::join('car_wash_order', 'car_wash_order_pay_record.order_id', '=', 'car_wash_order.order_id')
                ->join('users','car_wash_order.user_id', '=' ,'users.id')
                ->where('car_wash_order_pay_record.pay_type',6)
                ->where('car_wash_order_pay_record.status',1)
                ->where('users.type',2)
                ->where('car_wash_order.shop_id',$sc_user->shop_id)
                ->where('car_wash_order.user_id',$company_id)
                ->where('car_wash_order.status',1417)
                ->select(array('car_wash_order.user_id as pay_user_id','users.real_name as company_name','car_wash_order.order_id','car_wash_order_pay_record.amount',
                    'car_wash_order.pay_time as complete_time','car_wash_order.car_no','car_wash_order.verify_status','car_wash_order.verify_time',
                    // '"" as car_brand_id','"" as car_brand_name',
                    // '"" as car_series_id','""  as car_series_name',
                    // '"" as car_model_id','""  as car_model_name',
                    // '"" as model'
                    ))
                ->orderBy('car_wash_order.user_id','asc');
                if(Input::get('verify_status')!=""){
                    $cwr_orders=$cwr_orders->where('car_wash_order.verify_status',Input::get('verify_status'));
                }
                if(Input::get('car_no')!=""){
                    $cwr_orders=$cwr_orders->where('car_wash_order.car_no','like','%'.Input::get('car_no').'%');
                }
                if(Input::get('complete_time')!=""){
                    $arr=explode('~',Input::get('complete_time'));
                    $cwr_orders=$cwr_orders->whereBetween('car_wash_order.pay_time',array($arr[0]." 00:00:00",$arr[1]." 23:59:59"));
                }
                if(Input::get('order_id')!=""){
                    $cwr_orders=$cwr_orders->where('car_wash_order.order_id','like','%'.Input::get('order_id').'%');
                }
                $cwr_orders=$cwr_orders->get();
                foreach ($cwr_orders as $order) {
                    $order->return_type=0;
                    $order->amount=bcdiv($order->amount,100,2);
                    $order->order_type=1;
                    $order->car_brand_id="";
                    $order->car_brand_name="";
                    $order->car_series_id="";
                    $order->car_series_name="";
                    $order->car_model_id="";
                    $order->car_model_name="";
                    $order->model="";
                    $temp_array[]=$order;
                }
            }
            if($order_type==""||$order_type==2){
                //查询 挂账的套餐卡订单
                $sc_orders=ServiceCardOrderPayRecord::join('service_card_order', 'service_card_order_pay_record.order_id', '=', 'service_card_order.order_id')
                ->join('users','service_card_order.user_id', '=' ,'users.id')
                ->where('service_card_order_pay_record.pay_type',6)
                ->where('service_card_order_pay_record.status',1)
                ->where('users.type',2)
                ->where('service_card_order.shop_id',$sc_user->shop_id)
                ->where('service_card_order.user_id',$company_id)
                ->where('service_card_order.status',1417)
                ->select(array('service_card_order.user_id as pay_user_id','users.real_name as company_name','service_card_order.order_id','service_card_order_pay_record.amount',
                    'service_card_order.pay_time as complete_time','service_card_order.car_no','service_card_order.verify_status','service_card_order.verify_time',
                    // '"" as car_brand_id','"" as car_brand_name',
                    // '"" as car_series_id','""  as car_series_name',
                    // '"" as car_model_id','""  as car_model_name',
                    // '"" as model'
                    ))
                ->orderBy('service_card_order.user_id','asc');
                if(Input::get('verify_status')!=""){
                    $sc_orders=$sc_orders->where('service_card_order.verify_status',Input::get('verify_status'));
                }
                if(Input::get('car_no')!=""){
                    $sc_orders=$sc_orders->where('service_card_order.car_no','like','%'.Input::get('car_no').'%');
                }
                if(Input::get('complete_time')!=""){
                    $arr=explode('~',Input::get('complete_time'));
                    $sc_orders=$sc_orders->whereBetween('service_card_order.pay_time',array($arr[0]." 00:00:00",$arr[1]." 23:59:59"));
                }
                if(Input::get('order_id')!=""){
                    $sc_orders=$sc_orders->where('service_card_order.order_id','like','%'.Input::get('order_id').'%');
                }
                $sc_orders=$sc_orders->get();
                foreach ($sc_orders as $order) {
                    $order->return_type=0;
                    $order->amount=bcdiv($order->amount,100,2);
                    $order->order_type=2;
                    $order->car_brand_id="";
                    $order->car_brand_name="";
                    $order->car_series_id="";
                    $order->car_series_name="";
                    $order->car_model_id="";
                    $order->car_model_name="";
                    $order->model="";
                    $temp_array[]=$order;
                }
            }

            if($order_type==""||$order_type==0){
                //退货单列表
                $ro=ReturnOrder::leftJoin("orders","orders.order_id","=","return_order.order_id")
                ->leftJoin('users','orders.pay_user_id', '=' ,'users.id')
                ->leftJoin('return_order_record','return_order_record.return_order_id', '=' ,'return_order.id')
                ->where('users.type',2)
                ->where('return_order_record.pay_type',6)
                ->where("return_order.status",1)
                ->where('users.status',1)
                ->where('orders.place',2)
                ->where('orders.shop_id',$sc_user->shop_id)
                ->where('orders.pay_user_id',$company_id)
                ->select(array('orders.pay_user_id','users.real_name as company_name','return_order.id as order_id',
                    'return_order_record.amount','return_order.implement_time as complete_time','orders.car_no',
                    'return_order.verify_status','return_order.verify_time','orders.car_model_name as model',
                    'orders.car_brand_id as car_brand_id','orders.car_brand_name as car_brand_name',
                    'orders.car_series_id as car_series_id','orders.car_series_name as car_series_name',
                    'orders.car_model_id as car_model_id','orders.car_model_name as car_model_name',));
                if(Input::get('verify_status')!=""){
                    $ro=$ro->where('return_order.verify_status',Input::get('verify_status'));
                }
                if(Input::get('car_no')!=""){
                    $ro=$ro->where('orders.car_no','like','%'.Input::get('car_no').'%');
                }
                if(Input::get('complete_time')!=""){
                    $arr=explode('~',Input::get('complete_time'));
                    $ro=$ro->whereBetween('return_order.implement_time',array($arr[0]." 00:00:00",$arr[1]." 23:59:59"));
                }
                if(Input::get('order_id')!=""){
                    $ro=$ro->where('return_order.id','like','%'.Input::get('order_id').'%');
                }
                $ro=$ro->get();
                foreach ($ro as $_ro) {
                    $_ro->return_type=1;
                    $_ro->amount=-bcdiv($_ro->amount,100,2);
                    $_ro->order_type=0;
                    $temp_array[]=$_ro;
                }
            }
            if($order_type==""||$order_type==1){
                //洗车单的退货列表
                $rwo=ReturnCarwashOrder::leftJoin("car_wash_order","car_wash_order.order_id","=","return_carwash_order.order_id")
                ->leftJoin('users','car_wash_order.user_id', '=' ,'users.id')
                ->leftJoin('return_washorder_record','return_washorder_record.return_washorder_id', '=' ,'return_carwash_order.id')
                ->where('users.type',2)
                ->where('return_washorder_record.pay_type',6)
                ->where("return_carwash_order.status",1)
                ->where('car_wash_order.shop_id',$sc_user->shop_id)
                ->where('car_wash_order.user_id',$company_id)
                ->select(array('car_wash_order.user_id as pay_user_id','users.real_name as company_name','return_carwash_order.id as order_id',
                    'return_washorder_record.amount','return_carwash_order.implement_time as complete_time','car_wash_order.car_no',
                    'return_carwash_order.verify_status','return_carwash_order.verify_time',
                    // 'orders.car_model_name as model',
                    // 'orders.car_brand_id as car_brand_id','orders.car_brand_name as car_brand_name',
                    // 'orders.car_series_id as car_series_id','orders.car_series_name as car_series_name',
                    // 'orders.car_model_id as car_model_id','orders.car_model_name as car_model_name',
                    ));
                if(Input::get('verify_status')!=""){
                    $rwo=$rwo->where('return_carwash_order.verify_status',Input::get('verify_status'));
                }
                if(Input::get('car_no')!=""){
                    $rwo=$rwo->where('car_wash_order.car_no','like','%'.Input::get('car_no').'%');
                }
                if(Input::get('complete_time')!=""){
                    $arr=explode('~',Input::get('complete_time'));
                    $rwo=$rwo->whereBetween('return_carwash_order.implement_time',array($arr[0]." 00:00:00",$arr[1]." 23:59:59"));
                }
                if(Input::get('order_id')!=""){
                    $rwo=$rwo->where('return_carwash_order.id','like','%'.Input::get('order_id').'%');
                }
                $rwo=$rwo->get();
                foreach ($rwo as $_ro) {
                    $_ro->return_type=1;
                    $_ro->amount=-bcdiv($_ro->amount,100,2);
                    $_ro->order_type=1;
                    $_ro->car_brand_id="";
                    $_ro->car_brand_name="";
                    $_ro->car_series_id="";
                    $_ro->car_series_name="";
                    $_ro->car_model_id="";
                    $_ro->car_model_name="";
                    $_ro->model="";
                    $temp_array[]=$_ro;
                }
            }

            if($order_type==""||$order_type==2){
                //洗车单的退货列表
                $rwo=ReturnServiceCarOrder::leftJoin("service_card_order","service_card_order.order_id","=","return_service_card_order.order_id")
                ->leftJoin('users','service_card_order.user_id', '=' ,'users.id')
                ->leftJoin('return_service_card_record','return_service_card_record.return_order_id', '=' ,'return_service_card_order.id')
                ->where('users.type',2)
                ->where('return_service_card_record.pay_type',6)
                ->where("return_service_card_order.status",1)
                ->where('service_card_order.shop_id',$sc_user->shop_id)
                ->where('service_card_order.user_id',$company_id)
                ->select(array('service_card_order.user_id as pay_user_id','users.real_name as company_name','return_service_card_order.id as order_id',
                    'return_service_card_record.amount','return_service_card_order.implement_time as complete_time','service_card_order.car_no',
                    'return_service_card_order.verify_status','return_service_card_order.verify_time',
                    // 'orders.car_model_name as model',
                    // 'orders.car_brand_id as car_brand_id','orders.car_brand_name as car_brand_name',
                    // 'orders.car_series_id as car_series_id','orders.car_series_name as car_series_name',
                    // 'orders.car_model_id as car_model_id','orders.car_model_name as car_model_name',
                    ));
                if(Input::get('verify_status')!=""){
                    $rwo=$rwo->where('return_service_card_order.verify_status',Input::get('verify_status'));
                }
                if(Input::get('car_no')!=""){
                    $rwo=$rwo->where('service_card_order.car_no','like','%'.Input::get('car_no').'%');
                }
                if(Input::get('complete_time')!=""){
                    $arr=explode('~',Input::get('complete_time'));
                    $rwo=$rwo->whereBetween('return_service_card_order.implement_time',array($arr[0]." 00:00:00",$arr[1]." 23:59:59"));
                }
                if(Input::get('order_id')!=""){
                    $rwo=$rwo->where('return_service_card_order.id','like','%'.Input::get('order_id').'%');
                }
                $rwo=$rwo->get();
                foreach ($rwo as $_ro) {
                    $_ro->return_type=1;
                    $_ro->amount=-bcdiv($_ro->amount,100,2);
                    $_ro->order_type=2;
                    $_ro->car_brand_id="";
                    $_ro->car_brand_name="";
                    $_ro->car_series_id="";
                    $_ro->car_series_name="";
                    $_ro->car_model_id="";
                    $_ro->car_model_name="";
                    $_ro->model="";
                    $temp_array[]=$_ro;
                }
            }

            $response['result']=array("company_name"=>$company_name,"credit_list"=>$temp_array);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
        }

    /**
     * @Author:      lyt
     * @DateTime:    2017-02-10 18:22:53
     * @Description: 期初欠款 记录列表
     */
    public function beginLists(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                'company_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $company=Companys::find(Input::get("company_id"));
            $company_name=$company->name;
            $bar=BeginArrearRecords::
            leftJoin('sc_user as sc1','sc1.id','=','begin_arrear_records.created_by')
            ->leftJoin('sc_user as sc2','sc2.id','=','begin_arrear_records.verify_by')
            ->where("begin_arrear_records.shop_id",$sc_user->shop_id)->where("begin_arrear_records.company_id",Input::get("company_id"));            
            $finally=$bar->select(array("begin_arrear_records.*","sc1.real_name as create_name","sc2.real_name as veritf_name"))->get();

            $shop_amount=BeginArrear::where("shop_id",$sc_user->shop_id)->where("company_id",Input::get("company_id"))->sum("current_amount");
            $all_amount=BeginArrear::where("company_id",Input::get("company_id"))->sum("current_amount");
            foreach ($finally as $_f) {
                $_f->amount=$_f->amount/100;
                $_f->note=$_f->desc;
            }
            
            
            $response['result']=array("shop_amount"=>$shop_amount/100,"all_amount"=>$all_amount/100,"company_name"=>$company_name,"begin"=>$finally);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "beginLists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-28 16:50:28
     * @Description: 创建收款单
     */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_ids' => 'required',//[{'order_id':11323,"return_type":1,"order_type":1,}]
                'company_id' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_ids=json_decode(Input::get('order_ids'),1);
            $note=Input::get('note');
            $company_id=Input::get('company_id');
            $receivable_id=Input::get('receivable_id');
            $response=DB::transaction(function () use ($order_ids,$company_id,$note,$sc_user,$receivable_id) {
                $response = array('code' => 0, 'msg' => 'ok');
                $r=Receivable::find($receivable_id);
                if(is_null($r)){
                    $receivable_id=Common::createOrderId();
                    $receivable=new Receivable;
                    $receivable->receivable_id=$receivable_id;
                    $receivable->company_id=$company_id;
                    $receivable->note=$note;
                    $receivable->created_by=$sc_user->id;
                    $receivable->verify_status=0;
                    $receivable->shop_id=$sc_user->shop_id;
                    $receivable->type=1;
                    $receivable->save();
                }else{
                    $rp=ReceivablePay::where("receivable_id",$receivable_id)->whereIn("status",array(1,5,7))->first();
                    if($rp){//如果存在支付成功或者支付中 取消中的 不支持修改
                        $response = Lang::get("scs_error.receivable_pay_type_error_100005");
                        DB::rollback();
                        return $response;
                    }
                    ReceivableDetail::where('receivable_id',$receivable_id)->delete();
                }
                $amount=0;
                foreach($order_ids as $order_id){
                    $temp_rd=ReceivableDetail::leftJoin("receivable","receivable.receivable_id","=","receivable_detail.receivable_id")->where("receivable_detail.order_id",$order_id['order_id'])->where("receivable_detail.return_type",$order_id['return_type'])->where("receivable_detail.order_type",$order_id['order_type'])->where("receivable.status",1)->first();
                    if($temp_rd){
                        $response=Lang::get("scs_error.receivable_error_100002");
                        DB::rollback();
                        return $response;
                    }
                    $receivable_detail=new ReceivableDetail;
                    $receivable_detail->receivable_id=$receivable_id;
                    $receivable_detail->order_id=$order_id['order_id'];
                    $receivable_detail->return_type=$order_id['return_type'];
                    $receivable_detail->order_type=$order_id['order_type'];
                    $receivable_detail->save();

                    if($order_id['return_type']==0){
                        if($order_id['order_type']==0){
                            $order=Orders::find($order_id['order_id']);
                            if($order->verify_status==1){
                                $response=Lang::get("scs_error.receivable_error_100002");
                                DB::rollback();
                                return $response;
                            }
                            $topr=OrderPayRecord::where('order_id',$order_id['order_id'])->where("status",1)->where("pay_type",6)->sum("amount");
                            $amount+=$topr;
                        }else if($order_id['order_type']==1){
                            $order=CarWashOrder::find($order_id['order_id']);
                            if($order->verify_status==1){
                                $response=Lang::get("scs_error.receivable_error_100002");
                                DB::rollback();
                                return $response;
                            }
                            $topr=CarWashOrderPayRecord::where('order_id',$order_id['order_id'])->where("status",1)->where("pay_type",6)->sum("amount");
                            $amount+=$topr;
                        }else{  
                            $order=ServiceCardOrder::find($order_id['order_id']);
                            if($order->verify_status==1){
                                $response=Lang::get("scs_error.receivable_error_100002");
                                DB::rollback();
                                return $response;
                            }
                            $topr=ServiceCardOrderPayRecord::where('order_id',$order_id['order_id'])->where("status",1)->where("pay_type",6)->sum("amount");
                            $amount+=$topr;

                        }               
                    }else{
                        if($order_id['order_type']==0){
                            $return_order=ReturnOrder::find($order_id['order_id']);
                            if($return_order->verify_status==1){
                                $response=Lang::get("scs_error.receivable_error_100002");
                                DB::rollback();
                                return $response;
                            }
                            $topr=ReturnOrderRecord::where('return_order_id',$order_id['order_id'])->where("pay_type",6)->sum("amount");
                            $amount-=$topr;
                        }else if($order_id['order_type']==1){
                            $return_order=ReturnCarwashOrder::find($order_id['order_id']);
                            if(is_null($return_order)||$return_order->verify_status==1){
                                $response=Lang::get("scs_error.receivable_error_100002");
                                DB::rollback();
                                return $response;
                            }
                            $topr=ReturnWashOrderRecord::where('return_washorder_id',$order_id['order_id'])->where("pay_type",6)->sum("amount");
                            $amount-=$topr;
                        }else{  //套餐卡订单
                            $return_order=ReturnServiceCarOrder::find($order_id['order_id']);
                            if(is_null($return_order)||$return_order->verify_status==1){
                                $response=Lang::get("scs_error.receivable_error_100002");
                                DB::rollback();
                                return $response;
                            }
                            $topr=ReturnServiceCardRecord::where('return_order_id',$order_id['order_id'])->where("pay_type",6)->sum("amount");
                            $amount-=$topr;
                        }                      
                    }
                }
                $r=Receivable::find($receivable_id);
                $r->amount=$amount;
                $r->save();
                $response['result']=array('receivable_id'=>$receivable_id);
                return  $response;
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2017-02-11 12:25:09
     * @Description: 创建期初收回
     */
    public function createBeginReceive(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'amount' => 'required|min:0',//[{'order_id':11323,"return_type":1}]
                'company_id' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $company_id=Input::get('company_id');
            $amount=Input::get('amount')*100;
            $note=Input::get('note');
            $response=DB::transaction(function () use ($company_id,$note,$sc_user,$amount) {
                $response = array('code' => 0, 'msg' => 'ok');
                $ba=BeginArrear::where("shop_id",$sc_user->shop_id)->where("company_id",$company_id)->first();
                if(is_null($ba)||$amount>$ba->current_amount){//说明抹除的欠款 大于剩余的欠款总额
                    return $response = Lang::get("scs_error.begin_receive_error_90017");
                }                
                $receivable_id=Common::createOrderId();
                $receivable=new Receivable;
                $receivable->receivable_id=$receivable_id;
                $receivable->company_id=$company_id;
                $receivable->note=$note;
                $receivable->created_by=$sc_user->id;
                $receivable->verify_status=0;
                $receivable->shop_id=$sc_user->shop_id;
                $receivable->amount=$amount;
                $receivable->type=2;
                $receivable->save();
                $response['result']=array('receivable_id'=>$receivable_id);
                return  $response;
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "createBeginReceive", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-29 15:32:17
     * @Description: 收款单详情
     */
    public function detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok',"result"=>[]);
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable_id=Input::get('receivable_id');
            $r=Receivable::find($receivable_id);
            if(is_null($r)||$r->type==2){
                $response = Lang::get("scs_error.receivable_error_100001");
                break;
            }
            
            $company=Companys::find($r->company_id);
            $company_name=$company->name;
            $r=Receivable::find($receivable_id);
            $rd=ReceivableDetail::where('receivable_id',$receivable_id)->get();
            foreach($rd as $_rd){
                if($_rd->order_type==0){//如果是订单
                    if($_rd->return_type==0){
                        $orders=Orders::find($_rd->order_id);
                        $_rd->complete_time=$orders->pay_time;
                        $_rd->verify_status=$orders->verify_status;
                        $topr=OrderPayRecord::where('order_id',$_rd->order_id)->where("status",1)->where("pay_type",6)->sum("amount");
                        $_rd->amount=bcdiv($topr,100,2);
                    }else{
                        $return_order=ReturnOrder::find($_rd->order_id);
                        $orders=Orders::find($return_order->order_id);
                        $_rd->complete_time=$return_order->implement_time;
                        $_rd->verify_status=$return_order->verify_status;
                        $topr=ReturnOrderRecord::where('return_order_id',$_rd->order_id)->where("pay_type",6)->sum("amount");
                        $_rd->amount=-bcdiv($topr,100,2);
                    }
                    $_rd->car_no=$orders->car_no;
                    $_rd->car_brand_id=$orders->car_brand_id;
                    $_rd->car_brand_name=$orders->car_brand_name;
                    $_rd->car_series_id=$orders->car_series_id;
                    $_rd->car_series_name=$orders->car_series_name;
                    $_rd->car_model_id=$orders->car_model_id;
                    $_rd->car_model_name=$orders->car_model_name;
                    $_rd->model=$orders->car_model_name;
                    $_rd->verify_time=$r->verify_time;
                }else if($_rd->order_type==1){
                    if($_rd->return_type==0){
                        $orders=CarWashOrder::find($_rd->order_id);
                        $_rd->complete_time=$orders->pay_time;
                        $_rd->verify_status=$orders->verify_status;
                        $topr=CarWashOrderPayRecord::where('order_id',$_rd->order_id)->where("status",1)->where("pay_type",6)->sum("amount");
                        $_rd->amount=bcdiv($topr,100,2);
                    }else{
                        $return_order=ReturnCarwashOrder::find($_rd->order_id);
                        $orders=CarWashOrder::find($return_order->order_id);
                        $_rd->complete_time=$return_order->implement_time;
                        $_rd->verify_status=$return_order->verify_status;
                        $topr=ReturnWashOrderRecord::where('return_washorder_id',$_rd->order_id)->where("pay_type",6)->sum("amount");
                        $_rd->amount=-bcdiv($topr,100,2);
                    }
                    $_rd->car_no=$orders->car_no;
                    $_rd->car_brand_id="";
                    $_rd->car_brand_name="";
                    $_rd->car_series_id="";
                    $_rd->car_series_name="";
                    $_rd->car_model_id="";
                    $_rd->car_model_name="";
                    $_rd->model="";
                    $_rd->verify_time=$r->verify_time;
                }else{
                    if($_rd->return_type==0){
                        $orders=ServiceCardOrder::find($_rd->order_id);
                        $_rd->complete_time=$orders->pay_time;
                        $_rd->verify_status=$orders->verify_status;
                        $topr=ServiceCardOrderPayRecord::where('order_id',$_rd->order_id)->where("status",1)->where("pay_type",6)->sum("amount");
                        $_rd->amount=bcdiv($topr,100,2);
                    }else{
                        $return_order=ReturnServiceCarOrder::find($_rd->order_id);
                        $orders=ServiceCardOrder::find($return_order->order_id);
                        $_rd->complete_time=$return_order->implement_time;
                        $_rd->verify_status=$return_order->verify_status;
                        $topr=ReturnServiceCardRecord::where('return_order_id',$_rd->order_id)->where("pay_type",6)->sum("amount");
                        $_rd->amount=-bcdiv($topr,100,2);
                    }                    
                    $_rd->car_no=$orders->car_no;
                    $_rd->car_brand_id="";
                    $_rd->car_brand_name="";
                    $_rd->car_series_id="";
                    $_rd->car_series_name="";
                    $_rd->car_model_id="";
                    $_rd->car_model_name="";
                    $_rd->model="";
                    $_rd->verify_time=$r->verify_time;
                }
            }

            /**冲减明细**/
            $pays = ReceivablePay::where('receivable_id',$receivable_id)
                    ->where("pay_type",8)
                    ->where("status",1)
                    ->get()->toArray();
            $return_money = [];
            if(!empty($pays)){
                foreach ($pays as $pay) {
                    $recharges = AcountUserRechargeSpend::where("type",5)->where("buss_id",$pay['id'])->get()->toArray();
                    if (!empty($recharges)) {
                        foreach($recharges as $value){
                            $array = AcountUserRecharge::RechargeInfo($value['aurr_id']); //根据充值记录，查找对应的门店名称和账户标虚
                            $key = $array['shop_id'].'_'.$array['acount_type'];
                            if(isset($return_money[$key])){
                                $return_money[$key]['amount'] = round($return_money[$key]['amount']+bcdiv($value['amount'],100,6),2);
                            } else {
                                $return_money[$key] = $array;
                                $return_money[$key]['amount'] = round(bcdiv($value['amount'],100,6),2);
                            }
                        }
                    }
                }
            }
            $created_by_info = SCUser::select("real_name","shop_id")->where("id",$r->created_by)->get()->toArray();
            if (!empty($r->verify_by)){
                $verify_by_info = SCUser::select("real_name")->where("id",$r->verify_by)->get()->toArray();
            }else {
                $verify_by_info[0]['real_name'] = "";
            }
            $pay_record = ReceivablePay::where('receivable_id',$receivable_id)->where("status",1)->get();
            $shop_info = MaintenanceShops::select("name")->where("id",$created_by_info[0]['shop_id'])->get()->toArray();
            $response['result'] = [
                "company_id"=>$r->company_id,
                "pay_type"=>$r->pay_type,
                "company_name"=>$company_name,
                "amount"=>round(bcdiv($r->amount,100,6),2),
                "created_by_user"=>$created_by_info[0]['real_name'],
                "verify_by_user"=>$verify_by_info[0]['real_name'],
                "shop"=>$shop_info[0]['name'],
                "verify_time"=>$r->verify_time,
                "credit_list"=>$rd,
                "pay_record"=>$pay_record,
                "return_money"=>  array_values($return_money)
             ];
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2017-02-10 14:18:47
     * @Description: 期初欠款的
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-05-24 11:04:40
     * @Description: 暂时关闭 期初创建 调整 等接口 添加 进入方法 就退出逻辑
     */
    // public function beginCreate(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token' => 'required',
    //             'amount' => 'required',//[{'order_id':11323,"return_type":1}]
    //             'company_id' => 'required',
    //             'reocrd_type' => 'required|in:1,2',
    //         )
    //     );
    //     do{
    //         $response["result"]=$validator->messages()->all();
    //         break;
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.station_args_error_31001");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         //验证 授权
    //         if(Input::get('type')==1){
    //             $sc=SCUser::find(Input::get('id'));
    //             $area="010";
    //             $phone=$sc->phone;
    //             //判断验证码是否存在
    //             $record = UserCheckCodeUpgrade::where("business_type","beginreceivable")->where("phone",$phone)->first();
    //             if(is_null($record)){ //没有记录
    //                 $response = Lang::get("error.user_login_checkcode_null_1012");
    //                 break;
    //             }
    //             //校验是否超过时限
    //             if( time() > Common::datetime2Num($record->out_time_at) ){
    //                 $response = Lang::get("error.user_login_checkcode_timeout_1013");
    //                 break;
    //             }
            
    //             //校验验证码是否匹配
    //             if($record->check_code != Input::get('code')){
    //                 $response = Lang::get("error.user_login_checkcode_error_1014");
    //                 break;
    //             }
    //         }else{
    //             $sc=SCUser::where('user_name',Input::get('account'))->where('password',strtoupper(md5(Input::get('passwd'))))->where('status',1)->first();
    //             if(is_null($sc)){
    //                 $response = Lang::get("scs_error.scs_user_not_exiet21009");
    //                 break;
    //             }
    //             if($sc->title!=1){
    //                 $response = Lang::get("scs_error.login_user_error_21016");
    //                 break;
    //             }
    //         }


    //         $amount=Input::get('amount')*100;
    //         $note=Input::get('note');
    //         $company_id=Input::get('company_id');
    //         $reocrd_type=Input::get('reocrd_type');
    //         $user=Users::find($company_id);
    //         if(is_null($user)||$user->status!=1||$user->type!=2){
    //             $response = Lang::get("scs_error.user_error_21009");
    //             break;
    //         }

    //         $response=DB::transaction(function () use ($amount,$company_id,$note,$reocrd_type,$sc_user,$sc) {
    //             $response = array('code' => 0, 'msg' => 'ok');
    //             $ba=BeginArrear::where("shop_id",$sc_user->shop_id)->where("company_id",$company_id)->first();
    //             if(is_null($ba)){
    //                 $ba=new BeginArrear;
    //                 $ba->shop_id=$sc_user->shop_id;
    //                 $ba->company_id=$company_id;
    //                 $ba->current_amount=0;
    //                 $ba->amount=0;
    //                 $ba->created_by=$sc_user->id;
    //                 $ba->save();
    //             }
    //             if($reocrd_type==2){//如果是抹除欠款
    //                 if($amount>$ba->current_amount){//说明抹除的欠款 大于剩余的欠款总额
    //                     return $response = Lang::get("scs_error.begin_receive_error_90017");
    //                 }
    //                 $amount=-$amount;                    
    //             }
    //             $bar=new BeginArrearRecords;
    //             $bar->shop_id=$sc_user->shop_id;
    //             $bar->company_id=$company_id;
    //             $bar->type=$reocrd_type;
    //             $bar->amount=$amount;
    //             $bar->desc=$note;
    //             $bar->created_by=$sc_user->id;
    //             $bar->verify_by=$sc->id;
    //             $bar->verify_status=1;
    //             $bar->verify_time=Common::num2DateTime(time());
    //             $bar->save();
    //             $ba=BeginArrear::where("shop_id",$sc_user->shop_id)->where("company_id",$company_id)->first();
    //             $ba->current_amount=$ba->current_amount+$amount;
    //             $ba->amount=$ba->amount+$amount;
    //             $ba->save();

    //             $tran_no = date('YmdHis',time()).Common::generateCode(8);
    //             //记录公司账户收入
    //             Account::record_base('2',$tran_no,1,'0105',$amount,'期初欠款记录');


    //             $response['result']=array('receivable_id'=>$ba->id);
    //             return  $response;
    //         });
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "beginCreate", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }

    public function beginDetail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable_id=Input::get('receivable_id');
            $r=Receivable::find($receivable_id);
            if(is_null($r)||$r->type==1){
                $response = Lang::get("scs_error.receivable_error_100001");
                break;
            }
            $company=Companys::find($r->company_id);
            $r->company_name=$company->name;
            $sc=SCUser::find($r->created_by);
            $r->created_name=$sc->real_name;
            $r->amount=$r->amount/100;
            
            /**冲减明细**/
            $pays = ReceivablePay::where('receivable_id',$receivable_id)
                    ->where("pay_type",8)
                    ->where("status",1)
                    ->get()->toArray();
            $return_money = [];
            if(!empty($pays)){
                foreach ($pays as $pay) {
                    $recharges = AcountUserRechargeSpend::where("type",7)->where("buss_id",$pay['id'])->get()->toArray();
                    if (!empty($recharges)) {
                        foreach($recharges as $value){
                            $array = AcountUserRecharge::RechargeInfo($value['aurr_id']); //根据充值记录，查找对应的门店名称和账户标虚
                            $key = $array['shop_id'].'_'.$array['acount_type'];
                            if(isset($return_money[$key])){
                                $return_money[$key]['amount'] += round(bcdiv($value['amount'],100,6),2);
                            } else {
                                $return_money[$key] = $array;
                                $return_money[$key]['amount'] = round(bcdiv($value['amount'],100,6),2);
                            }
                        }
                    }
                }
            }
            $created_by_info = SCUser::select("real_name","shop_id")->where("id",$r->created_by)->get()->toArray();
            if (!empty($r->verify_by)){
                $verify_by_info = SCUser::select("real_name")->where("id",$r->verify_by)->get()->toArray();
            }else {
                $verify_by_info[0]['real_name'] = "";
            }
            $pay_record = ReceivablePay::where('receivable_id',$receivable_id)->where("status",1)->get();
            $shop_info = MaintenanceShops::select("name")->where("id",$created_by_info[0]['shop_id'])->get()->toArray();
            $response['result'] = [
                "company_id"=>$r->company_id,
                "pay_type"=>$r->pay_type,
                "company_name"=>$r->company_name,
                "amount"=>$r->amount,
                "created_by_user"=>$created_by_info[0]['real_name'],
                "verify_by_user"=>$verify_by_info[0]['real_name'],
                "shop"=>$shop_info[0]['name'],
                "verify_time"=>$r->verify_time,
                "pay_record"=>$pay_record,
                "return_money"=>  array_values($return_money),
                "receivable"=>$r,
             ];
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "beginDetail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author:      lyt
     * @DateTime:  2017-09-13 11:25:33
     * @Description: 添加收回单的支付记录
     */
    public function receive_paydesc(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable_id=Input::get("receivable_id");

            $receivable=Receivable::find($receivable_id);
            if(is_null($receivable)){
                $response = Lang::get("scs_error.receivable_error_100001");
                break;
            }
            // if($receivable->verify_status==1){
            //     $response = Lang::get("scs_error.receivable_error_100003");
            //     break;
            // }
            $user=Users::where("id",$receivable->company_id)
                ->leftJoin('user_account','user_account.user_id','=','users.id')
                ->select('users.id','users.phone','users.register_source_id','users.real_name','users.sex','users.type','user_account.account_no','user_account.balance','user_account.credit','users.u_dis')
                ->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.service_card_car_error_95015");
                break;
            }
            $cc=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3 and user_id=".$user->id);
            $bb=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type != 3 and user_id=".$user->id);
            $pay_amount=ReceivablePay::where('receivable_id',$receivable_id)->where('status',1)->sum("amount");
            $user->balance=$bb[0]->balance;
            $user->credit=$cc[0]->credit+$cc[0]->balance;
            $user->balance_amount=$receivable->amount;
            $user->payable_amount=$pay_amount;
            
            //订单支付记录
            $opr=ReceivablePay::where('receivable_id',$receivable_id)->whereIn('status',array(0,1,5,6,7))->select('id','status','pay_type','amount','created_by','tran_no',"sources")->get();
            $opr_amount=ReceivablePay::where('receivable_id',$receivable_id)->where('status',5)->sum("amount");
            $user->payin_amount=$opr_amount;
            $temp_arr=array("user_info"=>$user,"pay_record"=>$opr);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "receive_paydesc", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-09-13 16:24:43
     * @Description: 收款单的支付
     */
    public function receive_pay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
                'pay_type' => 'required',
                'amount' => 'required',
                'source' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable_id=Input::get("receivable_id");

            $receivable=Receivable::find($receivable_id);
            if(is_null($receivable)){
                $response = Lang::get("scs_error.receivable_error_100001");
                break;
            }
            if($receivable->verify_status==1){
                $response = Lang::get("scs_error.receivable_error_100006");
                break;
            }
            if($receivable->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.receivable_error_100007");
                break;
            }            
            $user=Users::find($receivable->company_id);
            // if(is_null($user)||$user->type==2||$user->status!=1){//客户不符合要求 
            //     $response = Lang::get("scs_error.service_card_car_error_95014");
            //     break;
            // }
            //取消 企业客户的过滤判断
            // if(is_null($user)||$user->status!=1){//客户不符合要求 
            //     $response = Lang::get("scs_error.service_card_car_error_95014");
            //     break;
            // }
            if(!isset(Receivable::$pay_type[Input::get("pay_type")])||!in_array(Input::get("source"),Receivable::$pay_type_source[Input::get("pay_type")])){
                $response = Lang::get("scs_error.receivable_pay_type_error_100004");
                break;
            }
            $response = Receivable::pay($receivable_id,Input::get("pay_type"),Input::get("amount"),$sc_user->id,Input::get("driver_id"),Input::get("source"));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "receiv_pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-09-14 10:31:34
     * @Description: 取消收款单的支付
     */
    public function cancel_receive_pay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
                'id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array("receivable_id"=>Input::get("receivable_id")));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable_id=Input::get("receivable_id");

            $receivable=Receivable::find($receivable_id);
            if(is_null($receivable)||$receivable->verify_status!=0){
                $response = Lang::get("scs_error.receivable_error_100001");
                break;
            }
            if($receivable->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.receivable_error_100007");
                break;
            } 

            $rp=ReceivablePay::find(Input::get("id"));
            if($rp->receivable_id!=$receivable->receivable_id){
                $response = Lang::get("scs_error.receivable_error_100011");
                break;
            }
            
            if($rp->status==5){//说明是支付中
                $response = Receivable::cancelPayIn($receivable_id,$rp->id);
            }else if($rp->status==1){
                //时间判断
                if(in_array($rp->pay_type, array(2,3))&&$rp->sources==2){
                    $response = Lang::get("scs_error.aur_undo_type_error_40126");
                    break;
                }
                if(date("Y-m-d",strtotime($rp->implement_time))!=date("Y-m-d",time())){
                    $response = Lang::get("scs_error.order_time_error_40115");
                    break;
                }
                $response = Receivable::cancel($receivable_id,$rp->id,$sc_user->id);
            }else if($rp->status==7){//说明是撤销中
                $response = Receivable::cancelCanceIn($receivable_id,$rp->id,$sc_user->id);
            }else{
                $response = Lang::get("scs_error.order_pay_error_40120");
                break;
            }            
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("receivable_id"=>$receivable_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancel_receive_pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    
    /**
     * @Author:      lyt
     * @DateTime:  2017-09-13 18:19:25
     * @Description: 用于完成收款单的
     */
    public function end_receive(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable_id=Input::get("receivable_id");
            
            if(Input::get('type')==1){
                $sc=SCUser::find(Input::get('id'));
                $area="010";
                $phone=$sc->phone;
                //判断验证码是否存在
                $record = UserCheckCodeUpgrade::where('business_id',$receivable_id)->where("business_type","receivable")->where("phone",$phone)->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
            
                //校验验证码是否匹配
                if($record->check_code != Input::get('code')){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }else{
                $sc=SCUser::where('user_name',Input::get('account'))->where('password',strtoupper(md5(Input::get('passwd'))))->where('status',1)->first();
                if(is_null($sc)){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1||$sc->shop_id!=$sc_user->shop_id){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
            }
            $receivable=Receivable::find($receivable_id);
            if(is_null($receivable)||$receivable->verify_status!=0){
                $response = Lang::get("scs_error.receivable_error_100001");
                break;
            }

            $pay_amount=ReceivablePay::where("receivable_id",$receivable_id)->where("status",1)->sum("amount");  
            if(floor($receivable->amount/100)!=floor($pay_amount/100)){
                $response = Lang::get("scs_error.receivable_pay_type_error_100010");
                break;
            }
            //如果没有任何成功支付记录不让结算 0元也要添加 0元支付记录
            $op=ReceivablePay::where("receivable_id",$receivable_id)->where("status",1)->first();   
            if(is_null($op)){
                $response = Lang::get("scs_error.receivable_pay_type_error_100010");
                break;
            }
            // $opu=ServiceCardOrderPayUndoRecord::where("order_id",$order->order_id)->where("status",0)->first();   
            // if($opu){
            //     $response = Lang::get("scs_error.receivable_pay_type_error_100010");
            //     break;
            // }

            if($receivable->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.receivable_error_100007");
                break;
            }        
            // 如果是订单收回 
            if($receivable->type==1){
                $t_mc=MemberCoefficient::where("status",1)->get();//获取所有的 订单类型 系数
                $temp_mc_arrauu=array();//构建订单类型 为键 系数为值的 数组
                foreach ($t_mc as $_mc) {
                    $temp_mc_arrauu[$_mc->source]=$_mc;
                }
                $ms=MaintenanceShops::find($sc_user->shop_id);//获取门店的 系数

                $time=date('Y-m-d H:i:s',time());
                $receivable_detail=ReceivableDetail::where('receivable_id',$receivable_id)->get();
                foreach($receivable_detail as $_rd){
                    if($_rd->return_type==0){                    
                        if($_rd->order_type==0){                            
                            Orders::where('order_id',$_rd->order_id)->update(array('verify_time'=>$time,'verify_status'=>1));
                            //计算积分
                            $order=Orders::find($_rd->order_id);
                            $temp_amount=OrderPay::where("order_id",$order->order_id)->where("status",1)->where("pay_type",6)->sum("amount");
                            $mc=$order->order_type==1?$temp_mc_arrauu[1]:$temp_mc_arrauu[2];
                            UserIntegralFlow::record($order->pay_user_id,$sc_user->shop_id,$order->order_id,1,$order->order_type==1?1001:1002,floor($temp_amount*$mc->integral*$ms->integral/100),'订单完成积分');
                            UserExperienceFlow::record($order->pay_user_id,$sc_user->shop_id,$order->order_id,1,$order->order_type==1?1001:1002,floor($temp_amount*$mc->experience*$ms->experience/100),'订单完成经验');

                        }else if($_rd->order_type==1){
                            CarWashOrder::where('order_id',$_rd->order_id)->update(array('verify_status'=>1,'verify_time'=>$time));  
                            //计算积分                            
                            $order=CarWashOrder::find($_rd->order_id);
                            $mc=$temp_mc_arrauu[4];
                            UserIntegralFlow::record($order->user_id,$order->shop_id,$order->order_id,1,1004,floor($order->pay_amount*$mc->integral*$ms->integral/100),'洗车订单完成积分');
                            UserExperienceFlow::record($order->user_id,$order->shop_id,$order->order_id,1,1004,floor($order->pay_amount*$mc->experience*$ms->experience/100),'洗车订单完成经验');
                        }else{
                            ServiceCardOrder::where('order_id',$_rd->order_id)->update(array('verify_status'=>1,'verify_time'=>$time)); 
                            //计算积分 
                            $order=ServiceCardOrder::find($_rd->order_id);
                            $temp_amount=ServiceCardOrderPayRecord::where("order_id",$order->order_id)->where("status",1)->where("pay_type",6)->sum("amount");
                            $mc=$temp_mc_arrauu[3];
                            UserIntegralFlow::record($order->user_id,$sc_user->shop_id,$order->order_id,1,1003,floor($temp_amount*$mc->integral*$ms->integral/100),'套餐卡销售订单完成积分');
                            UserExperienceFlow::record($order->user_id,$sc_user->shop_id,$order->order_id,1,1003,floor($temp_amount*$mc->experience*$ms->experience/100),'套餐卡销售订单完成经验');
                        }   
                    }else{
                        if($_rd->order_type==0){
                            ReturnOrder::where('id',$_rd->order_id)->update(array('verify_status'=>1,'verify_time'=>$time));
                            //计算积分
                            $return_order=ReturnOrder::find($_rd->order_id);
                            $order=Orders::find($return_order->order_id);
                            $temp_amount=ReturnOrderRecord::where('return_order_id',$return_order->id)->where("pay_type",6)->sum("amount");
                            $mc=$order->order_type==1?$temp_mc_arrauu[1]:$temp_mc_arrauu[2];
                            UserIntegralFlow::record($order->pay_user_id,$sc_user->shop_id,$return_order->id,2,$order->order_type==1?2001:2002,floor($temp_amount*$mc->integral*$ms->integral/100),'订单退款扣除积分');
                            UserExperienceFlow::record($order->pay_user_id,$sc_user->shop_id,$return_order->id,2,$order->order_type==1?2001:2002,floor($temp_amount*$mc->experience*$ms->experience/100),'订单退款扣除经验');

                        }else if($_rd->order_type==1){
                            ReturnCarwashOrder::where('id',$_rd->order_id)->update(array('verify_status'=>1,'verify_time'=>$time));

                            //计算积分         
                            $return_order=ReturnCarwashOrder::find($_rd->order_id);
                            $order=CarWashOrder::find($return_order->order_id);
                            $mc=$temp_mc_arrauu[4];
                            UserIntegralFlow::record($order->user_id,$order->shop_id,$return_order->id,2,2004,floor($order->pay_amount*$mc->integral*$ms->integral/100),'洗车订单退款扣除积分');
                            UserExperienceFlow::record($order->user_id,$order->shop_id,$return_order->id,2,2004,floor($order->pay_amount*$mc->experience*$ms->experience/100),'洗车订单退款扣除经验');
                        } else {
                            ReturnServiceCarOrder::where('id',$_rd->order_id)->update(array('verify_status'=>1,'verify_time'=>$time));

                            //计算积分         
                            $return_order=ReturnServiceCarOrder::find($_rd->order_id);
                            $order=ServiceCardOrder::find($return_order->order_id);
                            $temp_amount=ReturnServiceCardRecord::where('return_order_id',$return_order->id)->where("pay_type",6)->sum("amount");
                            $mc=$temp_mc_arrauu[3];
                            UserIntegralFlow::record($order->user_id,$order->shop_id,$return_order->id,2,2003,floor($temp_amount*$mc->integral*$ms->integral/100),'套餐卡订单退款扣除积分');
                            UserExperienceFlow::record($order->user_id,$order->shop_id,$return_order->id,2,2003,floor($temp_amount*$mc->experience*$ms->experience/100),'套餐卡订单退款扣除经验');
                        } 
                        
                    }
                }
                Users::checkMember($receivable->company_id);
            }
            $receivable->verify_by=$sc_user->id;
            $receivable->verify_time=date('Y-m-d H:i:s',time());
            $receivable->verify_status=1;
            $receivable->save();

            //推送微信信息            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("receivable_id"=>$receivable_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "end_receive", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-12-30 09:55:16
     * @Description: 执行收款单
     */
    /**
     * @Author:      lyt
     * @DateTime:    2017-02-11 12:44:40
     * @Description: 增加期初收回的逻辑
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-09-13 16:18:21
     * @Description: 开始符合支付和pos 支付废弃方法
     */
    // public function implement(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token' => 'required',
    //             'receivable_id' => 'required',
    //             'pay_type' => 'required',
    //         )
    //     );
    //     $receivable_id=Input::get('receivable_id');
    //     $response = array('code' => 0, 'msg' => 'ok');
    //     do{
    //         if($validator->fails()) {
    //             $response = Lang::get("scs_error.station_args_error_31001");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
    //         if(is_null($sc_user)){
    //             break;
    //         }
    //         $pay_type=Input::get("pay_type");
    //         if(!isset(Receivable::$pay_type[$pay_type])){//验证支付方式
    //             $response = Lang::get("scs_error.receivable_pay_type_error_100004");
    //             break;
    //         }
    //         if(Input::get('type')==1){
    //             $sc=SCUser::find(Input::get('id'));
    //             $area="010";
    //             $phone=$sc->phone;
    //             //判断验证码是否存在
    //             $record = UserCheckCodeUpgrade::where('business_id',$receivable_id)->where("business_type","receivable")->where("phone",$phone)->first();
    //             if(is_null($record)){ //没有记录
    //                 $response = Lang::get("error.user_login_checkcode_null_1012");
    //                 break;
    //             }
    //             //校验是否超过时限
    //             if( time() > Common::datetime2Num($record->out_time_at) ){
    //                 $response = Lang::get("error.user_login_checkcode_timeout_1013");
    //                 break;
    //             }
            
    //             //校验验证码是否匹配
    //             if($record->check_code != Input::get('code')){
    //                 $response = Lang::get("error.user_login_checkcode_error_1014");
    //                 break;
    //             }
    //         }else{
    //             $sc=SCUser::where('user_name',Input::get('account'))->where('password',strtoupper(md5(Input::get('passwd'))))->where('status',1)->first();
    //             if(is_null($sc)){
    //                 $response = Lang::get("scs_error.scs_user_not_exiet21009");
    //                 break;
    //             }
    //             if($sc->title!=1){
    //                 $response = Lang::get("scs_error.login_user_error_21016");
    //                 break;
    //             }
    //         }
    //         $receivable=Receivable::find(Input::get('receivable_id'));
    //         if(is_null($receivable)||$receivable->verify_status!=0){
    //             $response = Lang::get("scs_error.receivable_error_100001");
    //             break;
    //         }

    //         $receivable_detail=ReceivableDetail::where('receivable_id',Input::get('receivable_id'))->get();
    //         $response=Receivable::implement($receivable,$receivable_detail,$sc_user,$pay_type);
    //     }while(false);
    //     Log::info("info", array("system" => "scs" ,"event" => "implement", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }


    
    /**
     * @Author:      zwh
     * @DateTime:    2017-1-4 09:44:51
     * @Description: 发短信
     */
    public function sendMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                "receivable_id"=>'required'
            )
        );
       
        $response = array('code' => 0, 'msg' => 'ok','result'=>array());
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable_id=Input::get('receivable_id');
            $sc=SCUser::find(Input::get('id'));
            $phone=$sc->phone;
            $area='';
            $time_out_default = Config::get("user.time_out_default");
    
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id',$receivable_id)->where("business_type","receivable")->orderBy('out_time_at')->where("phone",$phone)->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，应收收回业务，您的授权码为'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                        ));
                    break;
                }else{ //超过限时
                    UserCheckCodeUpgrade::whereIn('business_id',$receivable_id)->where("business_type","receivable")->orderBy('out_time_at')->where("phone",$phone)->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，应收收回业务，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            $record = new UserCheckCodeUpgrade;
            $record->business_type="receivable";
            $record->business_id=$receivable_id;
            $record->phone=$phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;
            $record->save();

            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                ));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      lyt
     * @DateTime:    2017-02-10 14:29:07
     * @Description: 发送创建期初欠款的短息验证
     */
    public function sendBeginMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
            )
        );
       
        $response = array('code' => 0, 'msg' => 'ok','result'=>array());
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $sc=SCUser::find(Input::get('id'));
            $phone=$sc->phone;
            $area='';
            $time_out_default = Config::get("user.time_out_default");
    
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where("business_type","beginreceivable")->orderBy('out_time_at')->where("phone",$phone)->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，期初欠款业务，您的授权码为'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                        ));
                    break;
                }else{ //超过限时
                    UserCheckCodeUpgrade::where("business_type","beginreceivable")->orderBy('out_time_at')->where("phone",$phone)->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，期初欠款业务，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            $record = new UserCheckCodeUpgrade;
            $record->business_type="beginreceivable";
            $record->phone=$phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;
            $record->save();
            

            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                ));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "sendBeginMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    

    /**
     * @Author:      zwh
     * @DateTime:    2017-1-4 13:49:52
     * @Description: 删除收款单
     */
    public function delete(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
            )
        );
        $receivable_id=Input::get('receivable_id');
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $receivable=Receivable::find(Input::get('receivable_id'));
            if(is_null($receivable)){
                $response = Lang::get("scs_error.receivable_error_100001");
                break;
            }
            if($receivable->verify_status==1){
                $response = Lang::get("scs_error.receivable_error_100003");
                break;
            }
            $rp=ReceivablePay::where("receivable_id",Input::get('receivable_id'))->whereIn("status",array(1,5,7))->first();
            if($rp){//如果存在支付成功或者支付中 取消中的 不支持修改
                $response = Lang::get("scs_error.receivable_pay_type_error_100005");
                break;
            }
            $receivable->status=0;
            $receivable->save();
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "delete", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-1-4 14:32:20
     * @Description: 验证单号时候收回
     */
    public function checkOrders(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'receivable_id' => 'required',
            )
        );
        $receivable_id=Input::get('receivable_id');
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $rd=ReceivableDetail::where('receivable_id',$receivable_id)->get();
            foreach($rd as $_rd){
                if($_rd->return_type==0){                    
                    if($_rd->order_type==0){
                        $order=Orders::find($_rd->order_id);
                        if($order->verify_status==1){
                            $response = Lang::get("scs_error.receivable_error_100002");
                            break;
                        }
                        
                    }else if($_rd->order_type==1){
                        $order=CarWashOrder::find($_rd->order_id);
                        if($order->verify_status==1){
                            $response=Lang::get("scs_error.receivable_error_100002");
                            break;
                        }
                    }else{
                        $order=ServiceCardOrder::find($_rd->order_id);
                        if($order->verify_status==1){
                            $response=Lang::get("scs_error.receivable_error_100002");
                            break;
                        }
                    }
                }else{
                    if($_rd->order_type==0){
                        $ro=ReturnOrder::find($_rd->order_id);
                        if($ro->verify_status==1){
                            $response = Lang::get("scs_error.receivable_error_100002");
                            break;
                        }
                    }else{
                        $ro=ReturnCarwashOrder::find($_rd->order_id);
                        if($ro->verify_status==1){
                            $response = Lang::get("scs_error.receivable_error_100002");
                            break;
                        }
                    } 
                    
                }
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "checkOrders", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}